// pages/course/detail/detail.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    courseId: null,
    course: null,
    chapters: [],
    comments: [],
    loading: true,
    isEnrolled: false,
    showVideoPlayer: false,
    currentVideo: null,
    playProgress: 0,
    tabIndex: 0,
    showCommentInput: false,
    commentText: '',
    userInfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const courseId = options.id
    if (courseId) {
      this.setData({
        courseId: courseId
      })
      this.loadCourseDetail()
    } else {
      wx.showToast({
        title: '课程ID不能为空',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 检查登录状态
    this.checkLoginStatus()
    
    // 检查报名状态
    if (this.data.courseId) {
      this.checkEnrollStatus()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 暂停视频播放
    if (this.data.showVideoPlayer) {
      this.pauseVideo()
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 保存学习进度
    this.saveProgress()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadCourseDetail().finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.tabIndex === 2) {
      // 加载更多评论
      this.loadMoreComments()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const course = this.data.course
    return {
      title: course ? course.title : '精品课程推荐',
      path: `/pages/course/detail/detail?id=${this.data.courseId}`,
      imageUrl: course ? course.cover : '/images/share-bg.jpg'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline: function () {
    const course = this.data.course
    return {
      title: course ? course.title : '精品课程推荐',
      imageUrl: course ? course.cover : '/images/share-bg.jpg'
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus: function () {
    const app = getApp()
    const userInfo = app.globalData.userInfo
    
    this.setData({
      userInfo: userInfo
    })
  },

  /**
   * 加载课程详情
   */
  loadCourseDetail: function () {
    return new Promise((resolve, reject) => {
      wx.request({
        url: getApp().globalData.apiBase + `/courses/${this.data.courseId}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          if (res.data.success) {
            const course = res.data.data
            this.setData({
              course: course,
              chapters: course.chapters || [],
              loading: false
            })
            
            // 设置页面标题
            wx.setNavigationBarTitle({
              title: course.title
            })
          } else {
            wx.showToast({
              title: res.data.message || '加载失败',
              icon: 'none'
            })
          }
          resolve(res)
        },
        fail: (err) => {
          console.error('加载课程详情失败', err)
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          })
          this.setData({
            loading: false
          })
          reject(err)
        }
      })
    })
  },

  /**
   * 检查报名状态
   */
  checkEnrollStatus: function () {
    if (!wx.getStorageSync('token')) {
      return
    }
    
    wx.request({
      url: getApp().globalData.apiBase + `/courses/${this.data.courseId}/enroll-status`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            isEnrolled: res.data.data.isEnrolled,
            playProgress: res.data.data.progress || 0
          })
        }
      },
      fail: (err) => {
        console.error('检查报名状态失败', err)
      }
    })
  },

  /**
   * 加载评论
   */
  loadComments: function () {
    wx.request({
      url: getApp().globalData.apiBase + `/courses/${this.data.courseId}/comments`,
      method: 'GET',
      data: {
        page: 1,
        limit: 10
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            comments: res.data.data.list
          })
        }
      },
      fail: (err) => {
        console.error('加载评论失败', err)
      }
    })
  },

  /**
   * 加载更多评论
   */
  loadMoreComments: function () {
    // 实现加载更多评论逻辑
  },

  /**
   * Tab切换
   */
  onTabChange: function (e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      tabIndex: index
    })
    
    if (index === 2 && this.data.comments.length === 0) {
      this.loadComments()
    }
  },

  /**
   * 章节点击
   */
  onChapterTap: function (e) {
    const chapter = e.currentTarget.dataset.chapter
    
    if (!this.data.isEnrolled) {
      wx.showToast({
        title: '请先报名课程',
        icon: 'none'
      })
      return
    }
    
    if (chapter.videoUrl) {
      this.setData({
        currentVideo: chapter,
        showVideoPlayer: true
      })
    } else {
      wx.showToast({
        title: '该章节暂无视频',
        icon: 'none'
      })
    }
  },

  /**
   * 关闭视频播放器
   */
  closeVideoPlayer: function () {
    this.setData({
      showVideoPlayer: false,
      currentVideo: null
    })
  },

  /**
   * 暂停视频
   */
  pauseVideo: function () {
    const videoContext = wx.createVideoContext('courseVideo')
    videoContext.pause()
  },

  /**
   * 视频播放事件
   */
  onVideoPlay: function () {
    console.log('视频开始播放')
  },

  /**
   * 视频暂停事件
   */
  onVideoPause: function () {
    console.log('视频暂停')
  },

  /**
   * 视频结束事件
   */
  onVideoEnded: function () {
    console.log('视频播放结束')
    // 标记章节完成
    this.markChapterComplete()
  },

  /**
   * 视频时间更新
   */
  onVideoTimeUpdate: function (e) {
    const { currentTime, duration } = e.detail
    const progress = Math.floor((currentTime / duration) * 100)
    
    this.setData({
      playProgress: progress
    })
    
    // 定期保存进度
    if (progress % 10 === 0) {
      this.saveProgress()
    }
  },

  /**
   * 标记章节完成
   */
  markChapterComplete: function () {
    if (!this.data.currentVideo || !wx.getStorageSync('token')) {
      return
    }
    
    wx.request({
      url: getApp().globalData.apiBase + `/courses/${this.data.courseId}/chapters/${this.data.currentVideo.id}/complete`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.data.success) {
          // 更新章节状态
          const chapters = this.data.chapters.map(chapter => {
            if (chapter.id === this.data.currentVideo.id) {
              chapter.completed = true
            }
            return chapter
          })
          
          this.setData({
            chapters: chapters
          })
          
          wx.showToast({
            title: '章节学习完成',
            icon: 'success'
          })
        }
      },
      fail: (err) => {
        console.error('标记章节完成失败', err)
      }
    })
  },

  /**
   * 保存学习进度
   */
  saveProgress: function () {
    if (!this.data.currentVideo || !wx.getStorageSync('token')) {
      return
    }
    
    wx.request({
      url: getApp().globalData.apiBase + `/courses/${this.data.courseId}/progress`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      data: {
        chapterId: this.data.currentVideo.id,
        progress: this.data.playProgress
      },
      success: (res) => {
        console.log('进度保存成功')
      },
      fail: (err) => {
        console.error('保存进度失败', err)
      }
    })
  },

  /**
   * 报名课程
   */
  enrollCourse: function () {
    if (!wx.getStorageSync('token')) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认报名',
      content: `确定要报名《${this.data.course.title}》吗？`,
      success: (res) => {
        if (res.confirm) {
          this.doEnroll()
        }
      }
    })
  },

  /**
   * 执行报名
   */
  doEnroll: function () {
    wx.showLoading({
      title: '报名中...'
    })
    
    wx.request({
      url: getApp().globalData.apiBase + `/courses/${this.data.courseId}/enroll`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        wx.hideLoading()
        
        if (res.data.success) {
          this.setData({
            isEnrolled: true
          })
          
          wx.showToast({
            title: '报名成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data.message || '报名失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        wx.hideLoading()
        console.error('报名失败', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 显示评论输入框
   */
  showCommentInput: function () {
    if (!wx.getStorageSync('token')) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      showCommentInput: true
    })
  },

  /**
   * 隐藏评论输入框
   */
  hideCommentInput: function () {
    this.setData({
      showCommentInput: false,
      commentText: ''
    })
  },

  /**
   * 评论输入
   */
  onCommentInput: function (e) {
    this.setData({
      commentText: e.detail.value
    })
  },

  /**
   * 提交评论
   */
  submitComment: function () {
    const commentText = this.data.commentText.trim()
    
    if (!commentText) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      })
      return
    }
    
    wx.request({
      url: getApp().globalData.apiBase + `/courses/${this.data.courseId}/comments`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      data: {
        content: commentText
      },
      success: (res) => {
        if (res.data.success) {
          // 添加新评论到列表
          const newComment = res.data.data
          const comments = [newComment, ...this.data.comments]
          
          this.setData({
            comments: comments,
            showCommentInput: false,
            commentText: ''
          })
          
          wx.showToast({
            title: '评论成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data.message || '评论失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('提交评论失败', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 收藏课程
   */
  toggleFavorite: function () {
    if (!wx.getStorageSync('token')) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    
    const isFavorited = this.data.course.isFavorited
    const url = getApp().globalData.apiBase + `/courses/${this.data.courseId}/${isFavorited ? 'unfavorite' : 'favorite'}`
    
    wx.request({
      url: url,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            'course.isFavorited': !isFavorited
          })
          
          wx.showToast({
            title: isFavorited ? '取消收藏' : '收藏成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('收藏操作失败', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  }
})